<template>
  <div class="edit-maintenance-record">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <i class="el-icon-edit"></i>
            编辑维护记录
          </h2>
          <p class="page-subtitle">修改设备维护记录信息</p>
        </div>
        <div class="header-actions">
          <el-button @click="goBack" icon="el-icon-back" size="medium">
            返回
          </el-button>
          <el-button @click="viewDetail" icon="el-icon-view" size="medium">
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" v-loading="loading">
      <el-form
        ref="maintenanceFormRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="maintenance-form"
        size="medium"
        v-if="formData.equipmentMaintenanceId"
      >
        <!-- 设备信息区域 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-monitor"></i>
              设备信息
            </h3>
          </div>
          <div class="section-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="选择设备" prop="equipmentId">
                  <el-select
                    v-model="formData.equipmentId"
                    placeholder="请选择设备（可搜索）"
                    filterable
                    remote
                    :remote-method="searchEquipment"
                    :loading="equipmentLoading"
                    style="width: 100%"
                    @change="handleEquipmentChange"
                    clearable
                  >
                    <el-option
                      v-for="item in equipmentOptions"
                      :key="item.equipmentId"
                      :label="`${item.equipmentName} (${item.equipmentCode})`"
                      :value="item.equipmentId"
                    >
                      <span style="float: left">{{ item.equipmentName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.equipmentCode }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备编码" prop="equipmentCode">
                  <el-input v-model="formData.equipmentCode" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="设备名称" prop="equipmentName">
                  <el-input v-model="formData.equipmentName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备位置" prop="equipmentLocation">
                  <el-input v-model="formData.equipmentLocation" placeholder="请输入设备位置" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 维护信息区域 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-tools"></i>
              维护信息
            </h3>
          </div>
          <div class="section-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="维护类型" prop="maintenanceType">
                  <el-select v-model="formData.maintenanceType" placeholder="请选择维护类型" style="width: 100%">
                    <el-option label="预防性维护" value="preventive" />
                    <el-option label="故障维修" value="repair" />
                    <el-option label="定期保养" value="maintenance" />
                    <el-option label="紧急维修" value="emergency" />
                    <el-option label="升级改造" value="upgrade" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维护项目" prop="maintenanceItem">
                  <el-input
                    v-model="formData.maintenanceItem"
                    placeholder="请输入维护项目"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="维护人员" prop="maintenancePerson">
                  <el-input
                    v-model="formData.maintenancePerson"
                    placeholder="请输入维护人员姓名"
                    maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维护时间" prop="maintenanceTime">
                  <el-date-picker
                    v-model="formData.maintenanceTime"
                    type="datetime"
                    placeholder="请选择维护时间"
                    format="yyyy-MM-dd HH:mm"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="维护工时" prop="maintenanceHours">
                  <el-input-number
                    v-model="formData.maintenanceHours"
                    :min="0"
                    :precision="1"
                    placeholder="请输入维护工时"
                    style="width: 100%"
                    controls-position="right"
                  />
                  <div class="form-tip">单位：小时</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="维护费用" prop="maintenanceCost">
                  <el-input-number
                    v-model="formData.maintenanceCost"
                    :min="0"
                    :precision="2"
                    placeholder="请输入维护费用"
                    style="width: 100%"
                    controls-position="right"
                  />
                  <div class="form-tip">单位：元</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="维护状态" prop="status">
                  <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                    <el-option label="待处理" :value="0" />
                    <el-option label="已完成" :value="1" />
                    <el-option label="进行中" :value="2" />
                    <el-option label="已取消" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 故障信息区域 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-warning"></i>
              故障信息
            </h3>
          </div>
          <div class="section-content">
            <el-form-item label="故障现象" prop="faultDescription">
              <el-input
                v-model="formData.faultDescription"
                type="textarea"
                :rows="4"
                placeholder="请详细描述设备故障现象，包括故障发生时间、影响范围、故障表现等"
                maxlength="500"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>

            <el-form-item label="故障原因" prop="faultCause">
              <el-input
                v-model="formData.faultCause"
                type="textarea"
                :rows="3"
                placeholder="请分析故障产生的原因"
                maxlength="300"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 处理信息区域 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-s-tools"></i>
              处理信息
            </h3>
          </div>
          <div class="section-content">
            <el-form-item label="处理方案" prop="handlingSituation">
              <el-input
                v-model="formData.handlingSituation"
                type="textarea"
                :rows="4"
                placeholder="请描述维护处理方案，包括使用的工具材料、处理方法、处理步骤等"
                maxlength="500"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>

            <el-form-item label="处理结果" prop="handlingResult">
              <el-input
                v-model="formData.handlingResult"
                type="textarea"
                :rows="3"
                placeholder="请描述维护处理结果，包括是否解决问题、设备运行状态等"
                maxlength="300"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="使用材料" prop="materialsUsed">
                  <el-input
                    v-model="formData.materialsUsed"
                    placeholder="请输入使用的材料清单"
                    maxlength="200"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下次维护" prop="nextMaintenanceDate">
                  <el-date-picker
                    v-model="formData.nextMaintenanceDate"
                    type="date"
                    placeholder="请选择下次维护时间"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 其他信息区域 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">
              <i class="el-icon-document"></i>
              其他信息
            </h3>
          </div>
          <div class="section-content">
            <el-form-item label="备注信息" prop="remarks">
              <el-input
                v-model="formData.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入其他备注信息"
                maxlength="300"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>

            <el-form-item label="附件管理" prop="attachments">
              <div class="attachment-section">
                <!-- 现有附件 -->
                <div v-if="formData.attachments && formData.attachments.length > 0" class="existing-attachments">
                  <h4>现有附件</h4>
                  <div class="attachment-list">
                    <div 
                      v-for="(attachment, index) in formData.attachments" 
                      :key="index"
                      class="attachment-item"
                    >
                      <i class="el-icon-document"></i>
                      <span>{{ attachment.fileName }}</span>
                      <div class="attachment-actions">
                        <el-button type="text" size="small" icon="el-icon-view" @click="previewAttachment(attachment)">预览</el-button>
                        <el-button type="text" size="small" icon="el-icon-download" @click="downloadAttachment(attachment)">下载</el-button>
                        <el-button type="text" size="small" icon="el-icon-delete" @click="removeAttachment(index)" style="color: #F56C6C;">删除</el-button>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 上传新附件 -->
                <div class="upload-section">
                  <h4>添加新附件</h4>
                  <el-upload
                    class="upload-demo"
                    drag
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :before-upload="beforeUpload"
                    multiple
                    :file-list="fileList"
                  >
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传jpg/png/pdf文件，且不超过10MB</div>
                  </el-upload>
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>

      <!-- 无数据状态 -->
      <div v-else-if="!loading" class="no-data">
        <i class="el-icon-document"></i>
        <p>记录不存在或已被删除</p>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions" v-if="formData.equipmentMaintenanceId">
        <el-button @click="goBack" size="large">取消</el-button>
        <el-button @click="resetForm" size="large">重置</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" size="large">
          <i class="el-icon-check" v-if="!submitLoading"></i>
          保存修改
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { equipmentMaintenanceApi, equipmentApi } from '@/api/equipment'

export default {
  name: 'EditMaintenanceRecord',
  data() {
    return {
      loading: false,
      submitLoading: false,
      
      // 表单数据
      formData: {
        equipmentMaintenanceId: '',
        equipmentId: '',
        equipmentName: '',
        equipmentCode: '',
        equipmentLocation: '',
        maintenanceType: '',
        maintenanceItem: '',
        maintenancePerson: '',
        maintenanceTime: '',
        maintenanceHours: null,
        maintenanceCost: null,
        status: 0,
        faultDescription: '',
        faultCause: '',
        handlingSituation: '',
        handlingResult: '',
        materialsUsed: '',
        nextMaintenanceDate: '',
        remarks: '',
        attachments: []
      },
      
      // 表单验证规则
      formRules: {
        equipmentId: [
          { required: true, message: '请选择设备', trigger: 'change' }
        ],
        maintenanceType: [
          { required: true, message: '请选择维护类型', trigger: 'change' }
        ],
        maintenanceItem: [
          { required: true, message: '请输入维护项目', trigger: 'blur' }
        ],
        maintenancePerson: [
          { required: true, message: '请输入维护人员', trigger: 'blur' }
        ],
        maintenanceTime: [
          { required: true, message: '请选择维护时间', trigger: 'change' }
        ],
        maintenanceHours: [
          { required: true, message: '请输入维护工时', trigger: 'blur' }
        ],
        maintenanceCost: [
          { required: true, message: '请输入维护费用', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择维护状态', trigger: 'change' }
        ]
      },
      
      // 设备选项
      equipmentOptions: [],
      equipmentLoading: false,
      
      // 文件上传
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    }
  },
  
  mounted() {
    this.loadRecordDetail()
    this.loadEquipmentOptions()
  },
  
  methods: {
    // 加载记录详情
    async loadRecordDetail() {
      const recordId = this.$route.params.id
      if (!recordId) {
        this.$message.error('缺少记录ID参数')
        this.goBack()
        return
      }

      this.loading = true
      try {
        const response = await equipmentMaintenanceApi.getMaintenanceDetail(recordId)
        if (response.code === 200) {
          this.formData = { ...response.data }
          // 确保attachments是数组
          if (!this.formData.attachments) {
            this.formData.attachments = []
          }
        } else {
          this.$message.error(response.message || '获取记录详情失败')
          this.goBack()
        }
      } catch (error) {
        console.error('获取记录详情失败:', error)
        this.$message.error('获取记录详情失败')
        this.goBack()
      } finally {
        this.loading = false
      }
    },
    
    // 加载设备选项
    async loadEquipmentOptions() {
      this.equipmentLoading = true
      try {
        const response = await equipmentApi.getAllEquipmentNames()
        if (response.code === 200) {
          this.equipmentOptions = response.data || []
        }
      } catch (error) {
        console.error('加载设备列表失败:', error)
        this.$message.error('加载设备列表失败')
      } finally {
        this.equipmentLoading = false
      }
    },
    
    // 搜索设备
    async searchEquipment(query) {
      if (!query) {
        this.loadEquipmentOptions()
        return
      }
      
      this.equipmentLoading = true
      try {
        const response = await equipmentApi.getEquipmentPage({
          pageNum: 1,
          pageSize: 50,
          title: query
        })
        if (response.code === 200) {
          this.equipmentOptions = response.data.records || []
        }
      } catch (error) {
        console.error('搜索设备失败:', error)
      } finally {
        this.equipmentLoading = false
      }
    },
    
    // 设备选择改变
    handleEquipmentChange(equipmentId) {
      const selectedEquipment = this.equipmentOptions.find(item => item.equipmentId === equipmentId)
      if (selectedEquipment) {
        this.formData.equipmentName = selectedEquipment.equipmentName
        this.formData.equipmentCode = selectedEquipment.equipmentCode
        this.formData.equipmentLocation = selectedEquipment.equipmentLocation || ''
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        const valid = await this.$refs.maintenanceFormRef.validate()
        if (!valid) return

        this.submitLoading = true
        
        const response = await equipmentMaintenanceApi.updateMaintenance(this.formData)
        
        if (response.code === 200) {
          this.$message.success('维护记录更新成功')
          this.$router.push({ name: 'EquipmentMaintenance' })
        } else {
          this.$message.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('更新失败')
      } finally {
        this.submitLoading = false
      }
    },
    
    // 重置表单
    resetForm() {
      this.$confirm('确定要重置表单吗？所有修改将被撤销。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadRecordDetail()
        this.$message.success('表单已重置')
      }).catch(() => {
        this.$message.info('已取消重置')
      })
    },
    
    // 返回列表
    goBack() {
      this.$router.push({ name: 'EquipmentMaintenance' })
    },
    
    // 查看详情
    viewDetail() {
      if (this.formData.equipmentMaintenanceId) {
        this.$router.push({
          name: 'MaintenanceRecordDetail',
          params: { id: this.formData.equipmentMaintenanceId }
        })
      }
    },
    
    // 文件上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.formData.attachments.push({
          fileName: file.name,
          fileUrl: response.data.url,
          fileSize: file.size
        })
        this.$message.success('文件上传成功')
      } else {
        this.$message.error(response.message || '文件上传失败')
      }
    },
    
    // 文件上传失败
    handleUploadError(error, file, fileList) {
      console.error('文件上传失败:', error)
      this.$message.error('文件上传失败')
    },
    
    // 上传前检查
    beforeUpload(file) {
      const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isValidType) {
        this.$message.error('只能上传 JPG/PNG/PDF 格式的文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    
    // 预览附件
    previewAttachment(attachment) {
      if (attachment.fileUrl) {
        window.open(attachment.fileUrl, '_blank')
      } else {
        this.$message.warning('附件链接无效')
      }
    },
    
    // 下载附件
    downloadAttachment(attachment) {
      if (attachment.fileUrl) {
        window.open(attachment.fileUrl, '_blank')
      } else {
        this.$message.warning('附件链接无效')
      }
    },
    
    // 删除附件
    removeAttachment(index) {
      this.$confirm('确定要删除这个附件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formData.attachments.splice(index, 1)
        this.$message.success('附件已删除')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.edit-maintenance-record {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  color: white;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: white;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title i {
  font-size: 32px;
  color: #ffd700;
}

.page-subtitle {
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-weight: 400;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.header-actions .el-button:first-child {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.header-actions .el-button:first-child:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.main-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  min-height: 400px;
}

.maintenance-form {
  padding: 30px;
}

.form-section {
  margin-bottom: 40px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  background: linear-gradient(90deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #409EFF;
  font-size: 20px;
}

.section-content {
  padding: 25px;
}

.form-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

.attachment-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.existing-attachments h4,
.upload-section h4 {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 600;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.attachment-item i {
  color: #409EFF;
}

.attachment-item span {
  flex: 1;
  color: #606266;
}

.attachment-actions {
  display: flex;
  gap: 4px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 30px;
  border-top: 1px solid #ebeef5;
  background: #fafbfc;
}

.form-actions .el-button {
  min-width: 120px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.form-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 无数据状态 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.no-data i {
  font-size: 64px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.no-data p {
  font-size: 16px;
  margin: 0 0 20px 0;
}

/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 25px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item__content) {
  line-height: 1.4;
}

:deep(.el-input__inner) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  resize: vertical;
  line-height: 1.5;
}

:deep(.el-select .el-input__inner) {
  cursor: pointer;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  border-radius: 8px;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s ease;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background-color: #f5f7fa;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .edit-maintenance-record {
    padding: 10px;
  }
  
  .page-header {
    padding: 20px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .page-title {
    font-size: 22px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
  
  .maintenance-form {
    padding: 20px;
  }
  
  .section-content {
    padding: 15px;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
    padding: 20px;
  }
  
  .form-actions .el-button {
    width: 100%;
  }
  
  .attachment-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .attachment-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 18px;
  }
  
  .page-subtitle {
    font-size: 14px;
  }
  
  .maintenance-form {
    padding: 15px;
  }
  
  .section-content {
    padding: 10px;
  }
}
</style>